package cn.virens.common.mybatis.dynamic_table.annotations.config;

import cn.virens.common.mybatis.dynamic_table.annotations.handler.DynamicTableNameAnnotationSource;
import cn.virens.common.mybatis.dynamic_table.annotations.handler.DynamicTableNameMethodInterceptor;
import cn.virens.common.mybatis.dynamic_table.annotations.handler.DynamicTableNameMethodPointcutAdvisor;
import cn.virens.common.spring.annotations.config.VirAbstractImportAware;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.core.Ordered;

import java.lang.annotation.Annotation;

@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class DynamicTableNameConfiguration extends VirAbstractImportAware {

    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @Bean("dynamicTableNameAnnotationSource")
    public DynamicTableNameAnnotationSource dynamicTableNameAnnotationSource() throws Exception {
        return new DynamicTableNameAnnotationSource();
    }

    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @Bean("dynamicTableNameMethodInterceptor")
    public DynamicTableNameMethodInterceptor dynamicTableNameMethodInterceptor(//
                                                                               @Qualifier("dynamicTableNameAnnotationSource") DynamicTableNameAnnotationSource dynamicTableNameAnnotationSource//
    ) throws Exception {
        DynamicTableNameMethodInterceptor interceptor = new DynamicTableNameMethodInterceptor();
        interceptor.setAnnotationSource(dynamicTableNameAnnotationSource);

        return interceptor;
    }

    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @Bean("dynamicTableNameMethodPointcutAdvisor")
    public DynamicTableNameMethodPointcutAdvisor dynamicTableNameMethodPointcutAdvisor(//
                                                                                       @Qualifier("dynamicTableNameAnnotationSource") DynamicTableNameAnnotationSource dynamicTableNameAnnotationSource,//
                                                                                       @Qualifier("dynamicTableNameMethodInterceptor") DynamicTableNameMethodInterceptor dynamicTableNameMethodInterceptor//
    ) throws Exception {
        DynamicTableNameMethodPointcutAdvisor advisor = new DynamicTableNameMethodPointcutAdvisor();
        advisor.setOrder(getInteger("order", Ordered.LOWEST_PRECEDENCE));
        advisor.setAnnotationSource(dynamicTableNameAnnotationSource);
        advisor.setAdvice(dynamicTableNameMethodInterceptor);

        return advisor;
    }

    @Override
    protected Class<? extends Annotation> getAnnotationClass() {
        return EnableDynamicTableName.class;
    }

}
